<?php
namespace app\api\controller;

use app\BaseController;
use think\facade\Db;

class AppLogin extends Super
{

    /*
     * 登录
     * */
    public function index(){
        if(request()->isPost()){
            $data  = input('param.');

            $list = Db::table('member')->where('tel',$data['tel'])->find();

            if(!empty($list)){

                if($list['password'] == md5($data['password'])){

                    return json([
                        'msg' => '登录成功',
                        'code' => '200',
                        'user_token'=> $this->user_token($list),
                        'user_id'=>$list['id']
                    ]);
                }else{
                    return self::return_json('密码错误','0');
                }
            }else{
                return self::return_json('账号不存在','0');
            }
        }
    }

    /*
     * 注册
     * */
    public function register()
    {
        if(request()->isPost()){
            $data = input('param.');
            //判断是否发送验证码
            if(isset($data['type']) && $data['type'] = 'reg'){
                return $this->check_code($data['phone']);
            }else{

                $tel = Db::table('tel_code')->where('tel',$data['tel'])->find();
                if($tel['code'] == $data['code']){
                    if(Db::table('member')->where('tel',$data['tel'])->find()){
                        return $this->return_json('手机号已经注册','0');
                    }
                    $res = Db::table('member')->insert([
                                'tel'=>$data['tel'],
                                'password'=>md5($data['password']),
                                'create_time'=>time()
                            ]);
                    if($res){
                        return $this->return_json('注册成功','200');
                    }else{
                        return $this->return_json('注册失败','0');
                    }
                }else{
                    return $this->return_json('验证码错误','0');
                }
            }
        }
    }

    /*
     * 验证码
     * */
    public function check_code($tel){
        //发送验证码
        $code = rand(100000,999999);
        $this->send_sms($code,$tel);
        $tels = Db::table('tel_code')->where('tel',$tel)->find();
        if(empty($tels)){
            Db::table('tel_code')->insert([
                'tel'=>$tel,
                'code'=>$code,
                'create_time'=>time()
            ]);
        }else{
            Db::table('tel_code')->where('tel',$tel)->update([
                'code'=>$code,
                'create_time'=>time()
            ]);
        }
        return $this->return_json('验证码已经发送','200');
    }
}
